'use strict';

import React from 'react';
import {
  View,
  Image,
  PanResponder,
  Animated,
  Text,
  TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
import PixelRatio from 'PixelRatio';

import TImage from '../../components/TImage';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import ImageConstants from '../../common/ImageConstants';
import BaseComponent from './BaseComponent';
import PanResponderHelper from '../../common/PanResponderHelper';
import CommonRequestSliderImagesAction from '../../actions/common/CommonRequestSliderImagesAction';
import JumpToPageByUrlAction from '../../actions/common/JumpToPageByUrlAction';

const BANNER_IMGS = [
];

var windowWidth = Dimensions.get('window').width;
var IMAGE_WIDTH_MAIN = 670;
var IMAGE_WIDTH = 670;
var IMAGE_HEIGHT_MAIN = 340;
var IMAGE_HEIGHT = 320;

var IMAGE_SMALL_SCALE_MAIN = 1;
var IMAGE_SMALL_SCALE = 1;

const DEFAULT_NUM = 3;
const DEFAULT_IMAGES = ["", "", ""];

export default class CommonViewPagerMultiShow extends BaseComponent {
  constructor(props) {
    super(props);

    this.initTimer = null;

    this._midImageWidth = windowWidth;
    this._midImageWidth = windowWidth;
    this._midImageHeight = (this.props.type == Constants.SLIDER_TYPE.INDEX ? IMAGE_HEIGHT_MAIN : IMAGE_HEIGHT);
    this._midImageHeight = SizeUtils.translateDesignWidthToCode(this._midImageHeight);

    this._otherImageWidth = this._midImageWidth * (this.props.type == Constants.SLIDER_TYPE.INDEX ? IMAGE_SMALL_SCALE_MAIN : IMAGE_SMALL_SCALE);
    this._otherImageHeight = this._midImageHeight * (this.props.type == Constants.SLIDER_TYPE.INDEX ? IMAGE_SMALL_SCALE_MAIN : IMAGE_SMALL_SCALE);

    this._midX = (windowWidth - this._midImageWidth)/2;
    var otherTop = (this._midImageHeight - this._otherImageHeight)/2;

    // this._valueXY0 = {x:this._midX - (this._otherImageWidth + 10) * 2, y:otherTop};
    this._valueXY0 = {x:this._midX - (this._otherImageWidth), y:otherTop};
    //中间的
    this._valueXY1 = {x:this._midX, y:0};
    this._valueXY2 = {x:this._midX + this._midImageWidth, y:otherTop};
    // this._valueXY4 = {x:this._midX + this._midImageWidth + 10 + (this._otherImageWidth + 10), y:otherTop};

    // this.state.valueXY_0.setValue(this._valueXY0);
    // this.state.valueXY_1.setValue(this._valueXY1);
    // this.state.valueXY_2.setValue(this._valueXY2);
    // this.state.valueXY_3.setValue(this._valueXY3);
    // this.state.valueXY_4.setValue(this._valueXY4);

    this._valueWH_mid = {x:this._midImageWidth, y:this._midImageHeight};
    this._valueWH = {x:this._otherImageWidth, y:this._otherImageHeight};

    // this.state.valueWH_0.setValue(this._valueWH2);
    // this.state.valueWH_1.setValue(this._valueWH);
    // this.state.valueWH_2.setValue(this._valueWH);
    // this.state.valueWH_3.setValue(this._valueWH);
    // this.state.valueWH_4.setValue(this._valueWH);

    this.state = {
      valueXY_0: new Animated.ValueXY(this._valueXY1),
      valueXY_1: new Animated.ValueXY(this._valueXY2),
      valueXY_2: new Animated.ValueXY(this._valueXY0),
      // valueXY_3: new Animated.ValueXY(),
      // valueXY_4: new Animated.ValueXY(),

      valueWH_0: new Animated.ValueXY(this._valueWH_mid),
      valueWH_1: new Animated.ValueXY(this._valueWH),
      valueWH_2: new Animated.ValueXY(this._valueWH),
      // valueWH_3: new Animated.ValueXY(),
      // valueWH_4: new Animated.ValueXY(),
      zIndex: [0, 1, 0],

      data: [],
    }

    // console.log("_valueWH2", this._valueWH2);
    // console.log("_valueWH", this._valueWH);
    // console.log(this._valueXY2);
    // console.log(this._valueXY3);
    // console.log(this._valueXY4);

    this._currentMidIndex = 0;
    this._currentImageIndex = 0;
    this._autoPlay = true;
    this._autoPlayInterval;
    this._dragDirection = 0;
    this._animationCount = 0;
    this._isMini = true;

    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => {
        // console.log("onStartShouldSetPanResponder", event, gestureState.dx, this._animationCount);
        // return (this._animationCount <= 0)
        this._stopAllAnimation();
        PanResponderHelper.register(this);
        return true;
      },
      onPanResponderMove: (event, gestureState) => {
        // console.log("onPanResponderMove", event, gestureState.dx);
        if(Math.abs(gestureState.dx) > 10) {
          this._dragDirection = gestureState.dx < 0 ? 1 : -1;
        }
      },
      onPanResponderRelease: this._onRelease.bind(this),
    });
  }

  doRefresh() {
    this._requestData();
  }

  _onRelease() {
    // console.log("_onRelease", this._dragDirection);
    if(this._dragDirection != 0) {
      this._movePage(this._dragDirection);
    }
    else{
      this._dealClick();
    }
    this._dragDirection = 0;
    PanResponderHelper.unregister(this);
  }

  _dealClick() {
    let imageData = this.state.data[this._currentImageIndex];
    this._onPressImage(imageData);
  }

  _moveEnd(index) {
    this._animationCount = this._animationCount - 1;
    // console.log("_moveEnd", index, this._animationCount);
  }

  componentDidMount() {
    // this._movePage(1);
    this._startAutoPlay();
    this.initTimer = setTimeout(
      () => {
        // this._requestData();
      },
      500
    );
  }

  componentWillUnmount() {
    this.initTimer && clearTimeout(this.initTimer);
    clearInterval(this._autoPlayInterval);
  }

  componentWillUpdate(nextProps, nextState) {
    return true;
  }

  render() {
    return (
      <View style={{flexDirection:"row", height:this._midImageHeight}}>
        {this._renderItems()}
         <View style={{position:'absolute',bottom:0,right:20,height:SizeUtils.translateDesignHeightToCode(80),width:100,justifyContent: 'center',alignItems: 'flex-end',}}>
          <View style={{flexDirection:'row'}}>
            {
              this.state.data.map((item,index)=>{
                return this._renderPointIetm(index)
              })
            }            
          </View>
        </View> 
      </View>
    )
  }
  _renderPointIetm(index){
    return(<View key={index} style={{height:6,width:6,borderRadius:3,marginLeft:8,backgroundColor:this._currentImageIndex===index?'#fff':'#000'}}></View>)
  }

  _requestData() {
    new CommonRequestSliderImagesAction().call(this, {tag:this.props.type});
  }

  _getImageSource(index) {
    return BANNER_IMGS[index].path;
  }

  _renderItems() {
    return (
      <View style={{height:this._midImageHeight}}>
        {DEFAULT_IMAGES.map((data, index) => {return this._renderItem(index)})}
      </View>
    )
  }

  _renderItem(index) {
    // let images = Array.from(this.state.data);
    // for (var i = this.state.data.length; i < DEFAULT_NUM; i++) {
    //   images.push({image_url: ImageConstants.common_default_ad, isLocal:true})
    // }
    var data = {isLocal:true};
    if(this.state.data.length != 0) {
      var disIndex = index - this._currentMidIndex;
      if(disIndex == 2) {
        disIndex = -1;
      }
      else if (disIndex == -2) {
        disIndex = 1;
      }
      var imageIndex = disIndex + this._currentImageIndex;
      if(imageIndex >= this.state.data.length) {
        imageIndex = imageIndex - this.state.data.length;
      }
      else if(imageIndex < 0) {
        imageIndex = this.state.data.length + imageIndex
      }
      if(this.state.data.length > imageIndex) {
        data = this.state.data[imageIndex];
      }
    }
    // console.log("_renderItem", data, index, imageIndex, this.state);
      // this.state["valueWH_" + index].x, this.state["valueWH_" + index].y,
      // this.state["valueXY_" + index].x, this.state["valueXY_" + index].y);
    let source = null
    var imageWidth = this.state["valueWH_" + index].x;
    var imageHeight = this.state["valueWH_" + index].y;
    return(
      <Animated.View key={"item" + index} {...this._panResponder.panHandlers}
          style={{
            width:imageWidth,
            height:imageHeight,
            // width: this._midImageWidth,
            // height: this._midImageHeight,
            position: "absolute",
            left: this.state["valueXY_" + index].x,
            top: this.state["valueXY_" + index].y,
            zIndex: this.state.zIndex[index],
            justifyContent:"center",
            alignItems:"center",
            backgroundColor:"#eff1ff",
          }}>
          <TImage source={ImageConstants.common_default_ad} style={{width:64, height:55}} />
          {this._renderShowImage(data, imageWidth, imageHeight)}
        <Animated.View style={{width:imageWidth, height:SizeUtils.translateDesignHeightToCode(80), backgroundColor:"#00000066",bottom:SizeUtils.translateDesignWidthToCode(0),
            position:"absolute",justifyContent: 'center',}}>
          <Text style={{color:"#ffffff", fontSize:SizeUtils.translateFontSizeToCode(26),
              marginTop:SizeUtils.translateDesignHeightToCode(15),
              marginBottom:SizeUtils.translateDesignHeightToCode(15),
              shadowRadius:2,paddingLeft:SizeUtils.translateDesignWidthToCode(28), marginRight:SizeUtils.translateDesignWidthToCode(160),
              fontWeight:"bold"}} numberOfLines={1}>
            {data.desc}
          </Text>
        </Animated.View>
      </Animated.View>
    )
  }

  _renderShowImage(data, imageWidth, imageHeight) {
    if(!data.isLocal) {
      let image_url = data.image_url;
      if(this._isMini === true) {
        image_url += "?x-oss-process=style/mini300_q100";
      }
      return <Animated.Image source={{uri: image_url}}
                style={{width:imageWidth, height:imageHeight, position:"absolute", top:0, left:0}}
              />
    }
  }

  _onPressImage(data) {
    // new JumpToPageByUrlAction().call(this, "activity;58db7728ffc3c458d2f2a3e5");
    if(data) {
      new JumpToPageByUrlAction().call(this, data);
    }
  }

  _startAutoPlay() {
    if (!this._autoPlayInterval) {
      this._autoPlayInterval = setInterval(
        () => {
          this._movePage(1);
        },
        5000
      );
    }
  }

  //滚动 -1 left 1 right 0不变
  _movePage(direction) {
    // console.log("_movePage");
    if(this._animationCount > 0) {
      return;
    }
    this._currentMidIndex = this._currentMidIndex + direction;
    if(this._currentMidIndex >= DEFAULT_NUM) {
      this._currentMidIndex = 0;
    }
    else if(this._currentMidIndex < 0){
      this._currentMidIndex = DEFAULT_NUM - 1;
    }

    this._currentImageIndex = this._currentImageIndex + direction;
    if(this._currentImageIndex >= this.state.data.length) {
      this._currentImageIndex = 0;
    }
    else if(this._currentImageIndex < 0){
      this._currentImageIndex = this.state.data.length - 1;
    }

    this._animationCount = 1;
    var result = null;
    var valueWH = null;
    var springArr = [];
    var zIndex = [0, 0, 0];
    for (var i = 0; i < DEFAULT_NUM; i++) {
      result = this._getValueXY(i, direction);
      if(result[0] == this._valueXY1) {
        valueWH = this._valueWH_mid;
      }
      else {
        valueWH = this._valueWH;
      }
      zIndex[i] = result[2];
      springArr.push(Animated.timing(
        this.state["valueXY_" + i],
          {toValue: result[0],
          duration: result[1]}
      ));
      // console.log("Animated.spring", i, valueWH, this.state["valueXY_" + i]);
      springArr.push(Animated.timing(
        this.state["valueWH_" + i],
          {toValue: valueWH,
          duration: result[1]}
      ));
    }
    this.setState({
      zIndex: zIndex,
    })
    // console.log("this.state", this.state);
    Animated.parallel(springArr).start(() => {this._moveEnd()});
  }

  _stopAllAnimation() {
    for (var i = 0; i < DEFAULT_NUM; i++) {
      this.state["valueXY_" + i].stopAnimation(
        ({value}) => {}
      )
      this.state["valueWH_" + i].stopAnimation(
        ({value}) => {}
      )
    };
    this._animationCount = 0;
  }

  _getValueXY(index, direction) {
    if(index == this._currentMidIndex) {
      // console.log("currentMid:" + this._currentMidIndex + "pre:" + index + " to:" + 2);
      return [this._valueXY1, 500, 2];
    }
    else if(index < this._currentMidIndex) {
      if(this._currentMidIndex - index == 1) {
        // console.log("currentMid:" + this._currentMidIndex + "pre:" + index + " to:" + 1);
        if(direction == 1) {
          return [this._valueXY0, 500, 1];
        }
        else {
          return [this._valueXY0, 1, 0];
        }
      }
      else if(this._currentMidIndex - index == 2) {
        // console.log("currentMid:" + this._currentMidIndex + "pre:" + index + " to:" + 0);
        if(direction == 1) {
          return [this._valueXY2, 1, 0];
        }
        else {
          return [this._valueXY2, 500, 1];
        }
      }
    }
    else if(index > this._currentMidIndex) {
      if(index - this._currentMidIndex == 1) {
        // console.log("currentMid:" + this._currentMidIndex + "pre:" + index + " to:" + 3);
        if(direction == 1) {
          return [this._valueXY2, 1, 0];
        }
        else {
          return [this._valueXY2, 500, 1];
        }
      }
      else if(index - this._currentMidIndex == 2) {
        // console.log("currentMid:" + this._currentMidIndex + "pre:" + index + " to:" + 4);
        if(direction == 1) {
          return [this._valueXY0, 500, 1];
        }
        else {
          return [this._valueXY0, 1, 0];
        }
      }
    }
    return [0, 0, 10];
  }
}
